//@ts-ignore
import { defineStore } from 'pinia'

//第一个参数为本仓库的id，第二个参数为配置对象
export const myStore = defineStore('myStore',{
	state(){
		return {
			// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
			cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
			address:JSON.parse(uni.getStorageSync('address') || 'null'),
		}
	},
	//计算属性
	getters:{
		total(){
			let count = 0;
			this.cart.forEach(item=>{
				count += item.goods_count
			})
			return count;
		}
	},
	//方法
	actions:{
		updataAddress(add){
			this.address = add;
			this.saveToStorageAddress()
		},
		removeGoodsItem(i){
			this.cart.splice(i,1);
			this.saveToStorage();
		},
		updataCount(i,num){
			this.cart[i].goods_count = num;
			this.saveToStorage();
		},
		updataCart(i){
			this.cart[i].goods_state = !this.cart[i].goods_state;
			this.saveToStorage();
		},
		addCart(goods){
			//检查购物车数组中是否存在与当前相同的商品
			const goodsItem = this.cart.find(item=>{
				return goods.goods_id === item.goods_id;
			})
			//存在  数量++  不存在  push
			if(goodsItem){
				goodsItem.goods_count++;
			}else{
				this.cart.push(goods);
			}
			this.saveToStorage()
		},
		saveToStorage(){
			uni.setStorageSync("cart",JSON.stringify((this.cart)));
		},
		saveToStorageAddress(){
			uni.setStorageSync("address",JSON.stringify((this.address)));
		}
	}
})